package com.lglin.common.config.exception.handler;

import com.lglin.common.config.exception.SelfException;
import com.lglin.common.utils.reponse.ResultBean;
import com.lglin.common.utils.reponse.ResultEnum;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.multipart.MaxUploadSizeExceededException;

import javax.validation.ConstraintViolationException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(java.net.ConnectException.class)
    public ResultBean netConnectionTimeOut(Exception e) {
        System.out.println(e.getMessage());
        return ResultBean.fail().code(306).msg("网络连接超时");
    }

    @ExceptionHandler(SelfException.class)
    public ResultBean selfException(SelfException e) {
        return ResultBean.fail().code(e.getCode()).msg(e.getMessage());
    }

    @ExceptionHandler(ConstraintViolationException.class)
    public ResultBean selfException(ConstraintViolationException e) {
        //  return ResultBean.fail().code(400).msg(e.getMessage());
        return ResultBean.fail().msg(e.getMessage().split(": ")[1]);
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResultBean handleBindException(MethodArgumentNotValidException e) {
        //  return ResultBean.fail().code(400).msg(e.getMessage());
        String message = e.getMessage();
        String regex = "\\[(.*?)]";
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(message);
        String tip = null;
        while (matcher.find()) {
            tip = matcher.group(1);
        }
        return ResultBean.fail().msg(tip);
    }


    @ExceptionHandler(MaxUploadSizeExceededException.class)
    public ResultBean selfException(MaxUploadSizeExceededException e) {
        return ResultBean.fail().code(400).msg("单个文件大小不能超过2MB,总文件大小不能超过20MB");
    }
}
